using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Karma.Framework.Core.Domain.Tools.Utils;
using Karma.Framework.Core.Repository;
using log4net;

namespace Karma.Framework.Core.Domain.Tools.Export
{
    public class ExcelFileBuilder: IExcelFileBuilder
    {
        private static readonly ILog LOG = LogManager.GetLogger(typeof(ExcelFileBuilder).Name);

        public void BuildFile(Stream stream, QuerySpecification specification, QueryResult qresult)
        {
            if (LOG.IsDebugEnabled)
            {
                LOG.Debug(string.Format("Generating Excel documento for: {0}", specification.Metadata.Name));
            }
            var document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
            var workbookPart = document.AddWorkbookPart();
            workbookPart.Workbook = new Workbook();

            var worksheet = OpenXmlUtils.AddNewSheet(workbookPart, "Cognitum");

            if (LOG.IsDebugEnabled)
            {
                LOG.Debug("Generating headers...");
            }
            // headers
            for (var idx = 0; idx < specification.Metadata.Columns.Count; idx++)
            {
                var column = specification.Metadata.Columns[idx];
                if (LOG.IsDebugEnabled)
                {
                    LOG.Debug(string.Format("Generating column: {0}", column.Name));
                }
                var cell = OpenXmlUtils.AddNewCell(worksheet,  idx, 1);
                cell.CellValue = new CellValue(column.Name);
                cell.DataType = CellValues.String;
            }

            if (LOG.IsDebugEnabled)
            {
                LOG.Debug("set data....");
            }
            // data
            for (uint i = 0; i < qresult.Data.Length; i++)
            {
                if (LOG.IsDebugEnabled)
                {
                    LOG.Debug(string.Format("Generating row: {0}", i));
                }
                var row = (object[])qresult.Data[i];
                for (var j = 0; j < row.Length; j++)
                {
                    var data = row[j];
                    var cell = OpenXmlUtils.AddNewCell(worksheet, j, i + 2);
                    cell.CellValue = new CellValue(data.ToString());
                    cell.DataType = CellValues.String;
                }
            }

            document.Close();
        }
    }
}
